<?php


namespace App\Service;

use Simps\MQTT\Client;
use Simps\MQTT\Config\ClientConfig;

class MqttClientService
{
    public $client;

    public function __construct() {
        $this->getClient();
    }

    public function getClient()
    {
        if ($this->client) {
            return $this->client;
        }
        $config = [
            'userName' => 'dianbiao', // 用户名
            'password' => 'db@123456', // 密码
            'clientId' => Client::genClientID(), // 客户端id
            'keepAlive' => 120, // 默认0秒，设置成0代表禁用
            'protocolName' => 'MQTT', // 协议名，默认为MQTT(3.1.1版本)，也可为MQIsdp(3.1版本)
            'protocolLevel' => 4, // 协议等级，MQTT3.1.1版本为4，5.0版本为5，MQIsdp为3
            'properties' => [], // MQTT5 中所需要的属性
            'delay' => 3000, // 重连时的延迟时间 (毫秒)
            'maxAttempts' => -1, // 最大重连次数。默认-1，表示不限制
            'swooleConfig' => []
        ];
        $configObj = new ClientConfig($config);
        $this->client = new Client(env('MQTT_HOST', '47.111.230.9'), 1883, $configObj);
        $connect = $this->client->connect();
        sleep(3);
//        var_dump('mqtt connect', $connect,  $config);
        return $this->client;
    }
}
